import tkinter as tk
from tkinter import filedialog, messagebox
from datetime import datetime
from PIL import Image, ImageTk
from tkcalendar import DateEntry
import json
import os
import re
from .Edit import *
from .Mouse import *
from .Delete import *



def create_card(frame, task_name, priority, due_date, image_path):
    try:
        card_frame = tk.Frame(frame, relief=tk.RAISED, borderwidth=1, padx=10, pady=10)
        card_frame.pack(fill=tk.X, pady=5)

        task_label = tk.Label(card_frame, text=f"Task: {task_name}", anchor='w')
        task_label.pack(fill=tk.X)
        priority_label = tk.Label(card_frame, text=f"Priority: {priority}", anchor='w')
        priority_label.pack(fill=tk.X)
        due_date_label = tk.Label(card_frame, text=f"Due Date: {due_date}", anchor='w')
        due_date_label.pack(fill=tk.X)
        edit_button = tk.Button(card_frame, text="Edit", command=lambda: edit_task(card_frame, task_name, priority, due_date, image_path))
        edit_button.pack(anchor='s')
        delete_button = tk.Button(card_frame, text="Delete", command=lambda: delete_card(card_frame))
        delete_button.pack(anchor='s')
        created_time_label = tk.Label(card_frame, text=f"Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", anchor='w')
        created_time_label.pack(fill=tk.X)

        if image_path:
            try:
                img = Image.open(image_path)
                img = img.resize((100, 100))
                img = ImageTk.PhotoImage(img)
                image_label = tk.Label(card_frame, image=img)
                image_label.image = img
                image_label.pack()
            except IOError:
                messagebox.showerror("Error loading image", "The image file could not be opened or read.")

        # 绑定拖动相关的事件
        card_frame.bind('<Button-1>', lambda e, cf=card_frame: on_press(e, cf))
        card_frame.bind('<B1-Motion>', on_drag)
        card_frame.bind('<ButtonRelease-1>', on_release)

        # 保存卡片信息
        card_frame.task_name = task_name
        card_frame.priority = priority
        card_frame.due_date = due_date
        card_frame.image_path = image_path
        card_frame.original_frame = frame  # 记录原始框架

    except Exception as e:
        messagebox.showerror("Error creating card", str(e))

def on_release(event):
    global dragged_card
    if dragged_card:
        target_widget = window.winfo_containing(event.x_root, event.y_root)
        for col, frame in frames.items():
            if target_widget == frame or target_widget.winfo_parent() == frame:
                drop(dragged_card, frame)
                break
        else:
            drop(dragged_card, dragged_card.original_frame)  # 如果没有找到目标框架，则返回原始框架
        dragged_card = None

def drop(card_frame, target_frame):
    card_frame.place_forget()
    create_card(target_frame, card_frame.task_name, card_frame.priority, card_frame.due_date, card_frame.image_path)
    card_frame.destroy()